import EventPackage.EventManagerInterface;
import InstrumentationPackage.MessageWindow;
import util.FileConfigReader;
import util.FileReadingException;
import util.InvalidFileFormatException;
import EventPackage.Event;
import EventPackage.EventQueue;
import EventPackage.SensorEventManagerInterface;


public class FireSensor {

	public static void main(String[] args) {
		String EvtMgrIP;					// Event Manager IP address
		Event Evt;					// Event object
		EventQueue eq = null;				// Message Queue
		SensorEventManagerInterface em = null;	// Interface object to the event manager
		boolean Done = false;				// Loop termination flag
		String name = null;					// Name of sensor
		String description = null;			// Description of sensor
		int time_to_live = 0;				// Keep alive report time received by argument
		int retry_interval = 0;				// Time between retries of the keep alive messages
		int keepAliveReportTime = 0;		// Total duration of keep alive reports
        int	Delay = 2500;				// The loop delay (2.5 seconds)
		/////////////////////////////////////////////////////////////////////////////////
		// Get the IP address of the event manager
		/////////////////////////////////////////////////////////////////////////////////
		
        if(args.length < 1 || args.length > 2){
 			System.out.println("Wrong program initialization. Too many or too few arguments.\n The format should be:");
 			System.out.println("<programName> <config_filename> (optional: <EventMngrIP>)");
 			
 			System.exit(0);
 		}
 		FileConfigReader config;
		try {
			config = new FileConfigReader(args[0]);
			name = config.getName();
	 		description = config.getDescription();
	 		retry_interval = config.getRetryInterval();
	 		time_to_live = config.getTtl();
	 		keepAliveReportTime = config.getKeepAliveReportTime();
		
		} catch (FileReadingException e1) {
			System.out.println("Error reading configuration file:"+e1.getMessage());
			e1.printStackTrace();
		} catch (InvalidFileFormatException e1) {
			System.out.println("Error reading configuration file:"+e1.getMessage());
			e1.printStackTrace();
		}
 		

        MessageWindow mw = new MessageWindow("Fire Sensor log",0,0);
        EventManagerInterface.setMessageWindow(mw);
        mw.WriteMessage("Started Fire Sensor");

 		
		if ( args.length == 1 )
 		{
			// event manager is on the local system

			System.out.println("\n\nAttempting to register on the local machine..." );

			try
			{
				// Here we create an event manager interface object. This assumes
				// that the event manager is on the local machine

				em = new SensorEventManagerInterface(retry_interval, time_to_live, name, description, keepAliveReportTime);
				
			}

			catch (Exception e)
			{
				System.out.println("Error instantiating event manager interface: " + e);

			} // catch

		} else {

			// event manager is not on the local system

			EvtMgrIP = args[1];

			System.out.println("\n\nAttempting to register on the machine:: " + EvtMgrIP );

			try
			{
				// Here we create an event manager interface object. This assumes
				// that the event manager is NOT on the local machine

				em = new SensorEventManagerInterface(EvtMgrIP, retry_interval, time_to_live, name, description, keepAliveReportTime);
	
			}

			catch (Exception e)
			{
				System.out.println("Error instantiating event manager interface: " + e);

			} // catch

		} // if
 		// Here we check to see if registration worked. If ef is null then the
		// event manager interface was not properly created.
		
		if (em != null)
		{
			/********************************************************************
			** Here we start the main simulation loop
			*********************************************************************/

            FireSensorConsole console = new FireSensorConsole(em);
            console.start();

			while ( !Done )
			{

				try
				{
					eq = em.GetEventQueue();

				} // try

				catch( Exception e )
				{
					System.out.println("\t [-]Error getting event queue::" + e );

				} // catch

                if (eq == null) {
                    continue;
                }

				int qlen = eq.GetSize();

				for ( int i = 0; i < qlen; i++ )
				{
					Evt = eq.GetEvent();

					// If the event ID == 99 then this is a signal that the simulation
					// is to end. At this point, the loop termination flag is set to
					// true and this process unregisters from the event manager.

					if ( Evt.GetEventId() == 99 )
					{
						Done = true;
                        console.setDone(false);

						try
						{
							em.UnRegister();

				    	} // try

				    	catch (Exception e)
				    	{
				    		System.out.println("\t [-]Error unregistering: " + e);

				    	} // catch

				    	System.out.println("\n\n [-] Simulation Stopped. \n");

					} // if

				} // for

                if (qlen == 0) {
                    try
                    {
                        Thread.sleep( Delay );

                    } // try

                    catch( Exception e )
                    {
                        mw.WriteMessage("Sleep error:: " + e );

                    } // catch
                }

			} // while

		} else {

			System.out.println("Unable to register with the event manager.\n\n" );

		} // if

	}

}
